﻿using CoreLims.Models.CoreLims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Linq;
using System.Text;

namespace CoreLims.Controllers
{
    [Authorize(Roles = "Admin,设备管理")]
    public class EqController : Controller
    {
        private readonly CoreLimsContext dbContext;
        public EqController(CoreLimsContext context)
        {
            dbContext = context;
        }

        public ViewResult EqManager() => View();

        [HttpPost]
        public JsonResult GetEqList(string limit, string offset, string EqType) // 获取设备列表
        {
            var res = new Common.PageHelper();
            res.total = Eq.getEquipmentList(dbContext).Count();

            if (string.IsNullOrEmpty(EqType))
                res.rows = Eq.getEquipmentList(dbContext)
                           .Skip(int.Parse(offset)).Take(int.Parse(limit))
                           .Select(s => new { s.Id, s.Name, s.Status }).ToArray();
            else
                res.rows = Eq.getEquipmentList(dbContext)
                           .Where(s => s.Type == EqType)
                           .Skip(int.Parse(offset)).Take(int.Parse(limit))
                           .Select(s => new { s.Id, s.Name, s.Status }).ToArray();

            return Json(res);
        }

        [HttpPost]
        public JsonResult GetEquipmentInfo(string EqId) // 获取设备关联信息
        {
            var equipment = Eq.getEquipmentInfo(dbContext, EqId);
            return Json(equipment);
        }

        [HttpPost]
        public JsonResult GetEquipmentTypeList() // 获取设备类型列表
        {
            var list = Eq.getEquipmentList(dbContext).Distinct(new Eq.EquipmentTypeCompare())
                .Select(x => x.Type);
            return Json(list);
        }

        [HttpPost]
        public JsonResult GetEquipmentIdsByType(string type) // 按类型获取设备ID列表
        {
            var list = Eq.getEquipmentList(dbContext).Where(s => s.Type == type)
                .Select(x => x.Id);
            return Json(list);
        }

        [HttpPost]
        public JsonResult GetMaintainEventList(string EqId) // 获取设备关联的所有维护事件
        {
            var equipment = Eq.getMaintainEvents(dbContext, EqId);
            return Json(equipment);
        }

        [HttpPost]
        public JsonResult GetRelatedMaterials(string EqId) // 根据设备ID，获取设备相关的备件库存信息
        {
            var equipment = Eq.getEquipment(dbContext, EqId);
            var mlist = INV.Material.getMateriasByEqTypeId(dbContext, equipment.Type, equipment.Id);
            string[] ma = new string[mlist.Count()];
            int i = 0;
            foreach (var m in mlist)
            {
                ma[i] = m.Code;
                i++;
            }

            var inventorys = INV.Inventory.getInventoryList(dbContext)
                .Where(s => ma.Contains(s.MaterialCode) && s.Identification == "入库" && s.Status == "正常")
                .ToList();

            return Json(inventorys);
        }

        [HttpPost]
        public JsonResult GetMaintainEvent(string Id) // 获取指定的维护事件
        {
            var equipment = Eq.getMaintainEvent(dbContext, Id);
            return Json(equipment);
        }

        [HttpPost]
        public JsonResult GetMaintainList(string EventId, string limit, string offset) // 获取维护事件关联的所有维护记录
        {
            var list = Eq.getMaintainsByEventId(dbContext, EventId)
                            .Skip(int.Parse(offset)).Take(int.Parse(limit))
                            .ToArray();

            var res = new Common.PageHelper();
            res.total = Eq.getMaintainsByEventId(dbContext, EventId).Count;
            res.rows = list;

            return Json(res);
        }

        [HttpPost]
        public JsonResult GetUsageRecords(string limit, string offset, string EqId) // 获取设备使用记录
        {
            var res = new Common.PageHelper();
            res.total = Eq.getUsageRecords(dbContext, EqId).Count();

            res.rows = Eq.getUsageRecords(dbContext, EqId)
                        .Skip(int.Parse(offset)).Take(int.Parse(limit))
                        .ToArray();

            return Json(res);
        }

        [HttpPost]
        public string UpdateEquipmentStatus(string EqId) // 更新设备状态
        {
            return Eq.UpdateEquipmentStatus(dbContext, EqId);
        }

        [HttpPost]
        public string UpdateMaintainEventStatus(string Id) // 更新设备维护事件状态
        {
            return Eq.UpdateMaintainEventStatus(dbContext, Id);
        }

        [HttpPost]
        public string UpdateEquipmentScrap(string EqId) // 报废设备
        {
            return Eq.UpdateEquipmentScrap(dbContext, EqId);
        }

        [HttpPost]
        public string RemoveEquipment(string EqId) // 删除设备
        {
            return Eq.RemoveEquipment(dbContext, EqId);
        }

        [HttpPost]
        public string RemoveMaintainEvent(string Id) // 删除设备维护事件
        {
            return Eq.RemoveMaintainEvent(dbContext, Id);
        }

        [HttpPost]
        public string CreatEquipment(string EqId, string EqName, string EqType, string Site, string Group) // 新建设备
        {
            return Eq.CreatEquipment(dbContext, EqId, EqType, EqName, Site, Group);
        }

        [HttpPost]
        public string CreatMaintainEvent(string EqId, string EventsName, string Description) // 新建设备维护事件
        {
            var eq = Eq.getEquipment(dbContext, EqId);
            return Eq.CreatMaintainEvent(dbContext, EqId, EventsName, Description, eq.ResponsiblePerson, eq.ResponsiblePersonId);
        }

        [HttpPost]
        public string UpdateMaintainEventLastTime(string Id, string newTime) // 更新设备维护事件中的上次维护时间
        {
            return (Eq.UpdateMaintainEventLastTime(dbContext, Id, newTime));
        }

        [HttpPost]
        public string UpdateMaintainEventFrequency(string Id, string Frequency) // 更新设备维护事件中的频率
        {
            return (Eq.UpdateMaintainEventFrequency(dbContext, Id, Frequency));
        }

        [HttpPost]
        public string UpdateMaintainEventFrequencyUnit(string Id, string FrequencyUnit) // 更新设备维护事件中的频率单位
        {
            return (Eq.UpdateMaintainEventFrequencyUnit(dbContext, Id, FrequencyUnit));
        }

        [HttpPost]
        public string UpdateMaintainEventGroup(string Id, string SendToGroup, string SendToGroupId) // 更新设备维护事件中的消息接收组
        {
            return (Eq.UpdateMaintainGroup(dbContext, Id, SendToGroup, SendToGroupId));
        }

        [HttpPost]
        public string UpdateMaintainEventRemind(string Id, string Remind) // 更新设备维护事件中的提醒
        {
            return (Eq.UpdateMaintainEventRemind(dbContext, Id, Remind));
        }

        [HttpPost]
        public string UpdateEquipmentInfo(string eqStr, string infoStr) // 更新设备关联信息
        {
            var tempeq = JsonConvert.DeserializeObject<EqEquipment>(eqStr);  //反序列化，字符串转换为类
            var eq = Eq.getEquipment(dbContext, tempeq.Id);
            eq.Copy(tempeq);

            var elist = Eq.getMaintainEvents(dbContext, eq.Id);
            foreach (var e in elist)
            {
                e.SendToPerson = eq.ResponsiblePerson;
                e.SendToPersonId = eq.ResponsiblePersonId;
                dbContext.MaintainEvent.Update(e);
            }

            var info = JsonConvert.DeserializeObject<EqEquipmentInfo>(infoStr); // 扩展信息

            dbContext.Equipment.Update(eq);
            dbContext.EquipmentInfo.Update(info);
            dbContext.SaveChanges();

            return "设备及相关信息更新成功！";
        }

        [HttpPost]
        public string DoMaintainEvent(string jsonStr) // 执行维护操作
        {
            var maintain = JsonConvert.DeserializeObject<EqMaintain>(jsonStr);  //反序列化，字符串转换为类
            if (maintain.StarTime is null)
                return "开始时间不能为空";
            if (maintain.EndTime is null)
                return "结束时间不能为空";

            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            maintain.PersonId = user.Id;
            maintain.PersonName = user.FullName;

            return Eq.DoMaintainEvent(dbContext, maintain);
        }

        [HttpPost]
        public string DelRelatedMaterialAndEq(string Code) // 删除物料与设备的关联
        {
            return (INV.Material.DelRelatedMaterialAndEq(dbContext, Code));
        }

    }
}
